#!/bin/bash

# some config
es_data=/data/docker/data/elasticsearch #/home/wzq/data/es_data
es_container_id=$es_data/container_id # save the container id for restart
container_name=es_v1 # container name
image_name=cskin/es:v1 # image name

# create data folder
if [ ! -d "$es_data" ];then
	echo create folder $es_data
	mkdir -p $es_data
else
	# should chown ,otherwise may cause fail
	echo exists $es_data
fi

# prepare the container_id , default is 0
container_id=0
status=0 #0:not exist, 1 stop, 2 running
if [ -f "$es_container_id" ];then
	echo exists $es_container_id
	container_id=`cat $es_container_id`
	echo $container_id
	RUNNING=$(docker inspect --format="{{ .State.Running }}" $container_id 2> /dev/null)
	if [ ! $? -eq 0 ]; then
  		echo "no such container id=$es_container"
  		rm -f $es_container_id
  		docker rm -f $container_name
	elif [ "$RUNNING" == "false" ]; then
		status=1
	 	echo "container exists, but not running."
	else
	 	status=2
	 	echo "container already running"
	fi
fi


# start the container somehow
if [ "$status" == "0" ];then
	run_script="
	docker run -d \
	-v $es_data:/usr/share/elasticsearch/data \
	-p 127.0.0.1:9200:9200 -p 127.0.0.1:9300:9300 \
	--name=$container_name \
	$image_name "
	echo $run_script
	
	container_id=$($run_script)
	echo "start new container, id=$container_id"
	echo $container_id > $es_container_id

elif [ "$status" == "1" ]; then

	#statements
	container_id=$(docker restart $container_id)
	echo "restart container, id=$container_id"
fi
